#!/usr/bin/python
# -*- coding:utf-8 -*-

'''
Created on 11 juin 2014

@author: Alexandre Neuville
'''


from tkinter import Tk

from gui import MainWindow, MainMenu, ConfigurationWindow, ConnectionWindow, AboutWindow
from persistence import LoggerFactory, Database


class GuiApp(Tk):
    def __init__(self, app):
        super(GuiApp, self.__class__).__init__(self)
        self.__logger = LoggerFactory.getStdLogger(self)
        self.title("Console SQL")
        self.mainApp = app

        self.mainWindow = MainWindow(self)
        self.mainMenu = MainMenu(self)

        self.config(menu=self.mainMenu)
        self.profilesManager = ProfileManager(self.mainApp.config)
        self.profilesManager.loadProfiles()

        self.database = None
        self.dataInfos = {}

    def close(self):
        self.mainWindow.quit()

    def updateData(self):
        if not self.database:
            return

        with self.database as db:
            self.mainWindow.resetData()
            self.dataInfos.clear()
            for info in db.getDatabaseInformations():
                iid = self.mainWindow.addData(info)
                self.dataInfos[iid] = info

    def chooseActiveProfile(self):
        top = ConnectionWindow(self, self.profilesManager)
        if not top.result:
            return

        dsn, uid, pwd = top.result[1]
        self.database = Database(dsn, uid, pwd)
        self.updateData()

        return top.result[0]

    def disconnect(self, connIds):
        if not self.database:
            return False

        with self.database as db:
            for connId in connIds:
                connNumber = self.dataInfos[connId].number
                db.ejectConnection(connNumber)
            return True
    
    def configuration(self):
        ConfigurationWindow(self.mainWindow, self.profilesManager)

    def about(self):
        AboutWindow(self)

class ProfileManager(object):
    PROFILES = "profiles"
    DSN = "dsn"
    UID = "uid"
    PWD = "pwd"

    def __init__(self, config):
        self.config = config
        self.profiles = {}
        self.__logger = LoggerFactory.getStdLogger(self)

    def setProfile(self, profile, dsn, uid, pwd):
        self.profiles[profile] = (dsn, uid, pwd,)
        self.__logger.debug("Set profile : %s, dsn=%s, uid=%s", profile, dsn, uid)

    def getProfile(self, profile):
        return self.profiles.get(profile, None)

    def getProfiles(self):
        return self.profiles

    def loadProfiles(self):
        profiles = self.config.getParameter(ProfileManager.PROFILES)
        if profiles:
            for profile in profiles:
                mapValue = profiles.get(profile, {})
                self.setProfile(profile, mapValue.get(ProfileManager.DSN, ""), mapValue.get(ProfileManager.UID, ""),
                                mapValue.get(ProfileManager.PWD, ""))

        self.__logger.debug("Profiles loaded")
        return self.profiles

    def saveProfiles(self):
        profiles = {}
        for profile in self.profiles:
            (dsn, uid, pwd) = self.getProfile(profile)
            p = {}
            p[ProfileManager.DSN] = dsn
            p[ProfileManager.UID] = uid
            p[ProfileManager.PWD] = pwd
            profiles[profile] = p
        self.config.setParameter(ProfileManager.PROFILES, profiles)
        self.config.saveConfig()
        self.__logger.debug("Profiles saved")
        
    def existProfile(self, profile):
        return profile in self.profiles

    def deleteProfile(self, profile):
        self.profiles.pop(profile, None)
        self.__logger.debug("Profile deleted : %s", profile)


class ConsoleApp(object):
    def __init__(self, jsonConfig):
        self.config = jsonConfig

    def executeApp(self):
        app = GuiApp(self)
        app.mainloop()
